<template>
  <div>
    <BasicTable @register="registerTable">
      <template #headerTop>
        <Alert v-if="checkedKeys.length > 0" type="info" show-icon style="position: relative">
          <template #message>
            <div>
              <span>已选中{{ checkedKeys.length }}条记录</span>
              <div style="position: absolute; top: 4px; right: 10px">
                <Tooltip title="删除">
                  <a-button type="text" @click="handleSelectedDelete">
                    <Icon :icon="ICON.DELETE" color="#0960bd" />
                  </a-button>
                </Tooltip>
              </div>
            </div>
          </template>
        </Alert>
      </template>
      <template #toolbar>
        <a-button type="primary" size="middle" @click="addCustomerClick"> 添加租户 </a-button>
      </template>
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'action'">
          <TableAction
            :actions="[
              {
                icon: 'ant-design:edit-filled',
                tooltip: {
                  title: '编辑',
                  placement: 'top',
                },
                onClick: handleEdit.bind(null, record),
              },
              {
                icon: 'ant-design:eye-filled',
                tooltip: {
                  title: '详情',
                  placement: 'top',
                },
                onClick: handleMore.bind(null, record),
              },
              {
                icon: 'ant-design:delete-outlined',
                tooltip: {
                  title: '删除',
                  placement: 'top',
                },
                onClick: handleDelete.bind(null, record),
              },
            ]"
            :drop-down-actions="[
              {
                icon: 'ant-design:user-delete-outlined',
                label: '管理客户用户',
                onClick: handleUser.bind(null, record),
              },
            ]"
          />
        </template>
      </template>
    </BasicTable>
    <PublicDrawer
      @register="registerDrawer"
      :show-tabs="['detail', 'attribute', 'telemetry', 'alarm', 'event', 'association']"
      updateDescData="handleUpdateDescData"
    />
    <AddTenant @register="addCustomerRegister" @close-model-flag="closeModelFlag" />
  </div>
</template>

<script lang="ts" setup>
  import AddTenant from './components/AddTenant.vue';
  import { ICON } from '/@/enums/iconEnum';
  import Icon from '/@/components/Icon';
  import { Alert, Tooltip } from 'ant-design-vue';
  import { BasicTable, useTable, TableAction } from '/@/components/Table';
  import { customersColumns, searchFormSchema, tenantDetailSchema } from './components/tenant.data';
  import { useGo } from '/@/hooks/web/usePage';
  import { useModal } from '/@/components/Modal';
  import { onMounted, ref } from 'vue';
  import dayjs from 'dayjs';
  import { useDrawer } from '/@/components/Drawer';
  import { useMessage } from '/@/hooks/web/useMessage';
  import PublicDrawer from '/@/components/thingsborad/sharedComponents/modules/PublicDrawer/index.vue';
  import { ENTITY_TYPE } from '/@/components/thingsborad/sharedComponents/modules/PublicDrawer/index.data';
  import { tableFormStyleSetting, tableStyleSetting } from '/@/settings/thingsBoardDesign';
  import {
    getTenantInfos,
    deleteTheTenant,
    getTheTenantById,
  } from '/@/api/thingsborad/tenant/tenant';
  import { tenantParams } from '/@/api/thingsborad/tenant/model/tenantModel';
  //应用路由
  const go = useGo();
  //获取登录用户数据
  const { createConfirm } = useMessage();
  //全选数据
  const checkedKeys = ref<any>([]);
  //表格数据
  let customerDataList = ref<Array<any>>([]);
  //请求参数
  let params = ref<tenantParams>({
    pageSize: 10,
    page: 0,
    sortProperty: 'createdTime',
    sortOrder: 'DESC',
  });

  //生命周期函数
  onMounted(() => {
    // 获取表格数据
    setProps({
      api: getTenantInfos,
      beforeFetch: (val) => {
        params.value.page = val.page - 1;
        params.value.pageSize = val.pageSize;
        params.value.sortOrder = val.order == 'ascend' ? 'ASC' : 'DESC';
        params.value.sortProperty = 'createdTime';

        if (val.deptName === null) {
          params.value.textSearch = undefined;
        } else {
          params.value.textSearch = val.deptName;
        }
        return params.value;
      },
      afterFetch: (res) => {
        customerDataList.value = [];
        if (res.length === 0) {
          return customerDataList.value;
        }

        res.forEach((item) => {
          customerDataList.value.push({
            createdTime: dayjs(item.createdTime).format('YYYY-MM-DD HH:mm:ss'),
            title: item.title,
            email: item.email === null ? '--' : item.email,
            tenantProfileName: item.tenantProfileName === null ? '--' : item.tenantProfileName,
            country: item.country === null ? '--' : item.country,
            city: item.city === null ? '--' : item.city,
            id: item.id.id,
            entityType: item.id.entityType,
          });
        });

        return customerDataList.value;
      },
      fetchSetting: {
        pageField: 'page',
        sizeField: 'pageSize',
        listField: 'data',
        totalField: 'totalElements',
      },
    });
  });
  //抽屉初始化
  const [registerDrawer, { openDrawer }] = useDrawer();
  //弹窗初始化
  const [addCustomerRegister, { openModal, setModalProps, closeModal }] = useModal();
  //表格初始化
  const [registerTable, { reload, setProps }] = useTable({
    title: '租户',
    columns: customersColumns,
    ...tableStyleSetting,
    formConfig: {
      layout: 'horizontal',
      schemas: searchFormSchema,
      showAdvancedButton: false,
      submitFunc: async () => {
        reload();
      },

      ...tableFormStyleSetting,
      actionColOptions: {
        md: { span: 8, offset: 16 },
        lg: { span: 6, offset: 16 },
        xl: { span: 4, offset: 16 },
        xxl: { span: 4, offset: 16 },
      },
    },
    rowKey: 'id',
    rowSelection: {
      type: 'checkbox',
      selectedRowKeys: checkedKeys,
      onSelect: onSelect,
      onSelectAll: onSelectAll,
    },
  });
  //删除租户
  const handleDelete = (record: Recordable) => {
    createConfirm({
      iconType: 'info',
      title: `确定要删除租户    '${record.title}'   吗？`,
      content: '请注意：确认后，客户及其所有相关数据将不可恢复。',
      onOk: async () => {
        await deleteTheTenant(record.id);
        await reload();
      },
    });
  };
  //详情
  const handleMore = (record: Recordable) => {
    openDrawer(true, {
      entityType: ENTITY_TYPE.TENANT,
      entityId: record.id,
      title: record.title,
      api: getTheTenantById,
      detailSchema: tenantDetailSchema,
      params: record.id,
    });
  };
  // 多选删除
  const handleSelectedDelete = () => {
    createConfirm({
      iconType: 'info',
      title: `确定要删除    '${checkedKeys.value.length}'   个租户吗？`,
      content: '请注意：确认后，租户及其所有相关数据将不可恢复。',
      onOk: async () => {
        for (const item of checkedKeys.value) {
          await deleteTheTenant(item);
        }
        reload();
        checkedKeys.value = [];
      },
    });
  };
  // 多选
  function onSelect(record, selected) {
    if (selected) {
      checkedKeys.value = [...checkedKeys.value, record.id];
    } else {
      checkedKeys.value = checkedKeys.value.filter((id) => id !== record.id);
    }
  }
  // 全选
  function onSelectAll(selected, _selectedRows, changeRows) {
    const changeIds = changeRows.map((item) => item.id);
    if (selected) {
      checkedKeys.value = [...checkedKeys.value, ...changeIds];
    } else {
      checkedKeys.value = checkedKeys.value.filter((id) => {
        return !changeIds.includes(id);
      });
    }
  }
  //编辑客户
  const handleEdit = (record: Recordable) => {
    setModalProps({
      width: 800,
      title: '编辑客户',
      okText: '保存',
    });
    openModal(true, record);
  };
  // 管理客户用户
  const handleUser = (record: Recordable) => {
    go({
      name: 'ManageTenant',
      params: {
        id: record.id,
        name: record.title,
        entityType: record.entityType,
      },
    });
  };

  // 添加客户点击事件
  const addCustomerClick = () => {
    setModalProps({
      width: 800,
      title: '添加客户',
      okText: '保存',
    });
    openModal(true, true);
  };
  // 关闭弹窗
  const closeModelFlag = () => {
    closeModal();
    reload();
  };
</script>
